package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApCollectionService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {
    @Autowired
    private CacheService cacheService;

    /**
     * 文章收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //检查参数
        if(dto==null || dto.checkParam()){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询
        String collection = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId().toString(), dto.getEntryId().toString());
        if(StringUtils.isNotBlank(collection) && dto.getOperation()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已经收藏了");
        }
        log.info("collection:{}",collection);
        if(dto.getOperation()==0){
            //收藏
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId().toString(), dto.getEntryId().toString(), JSON.toJSONString(dto));
        }else {
            //取消收藏
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId().toString(), dto.getEntryId().toString(), JSON.toJSONString(dto));
        }
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
